<script setup lang="ts">
import { OnlineStatus, LockStatus, BikeType } from '@/types/enum'
import { computed, watchEffect, ref } from 'vue'
import { queryBike } from '@/api/bike'
import { getToken } from '@/utils/cache/cookies'
import { queryBikeTableCol } from '@/api/bike/types/bike'
import { useRouter } from 'vue-router'
// Props
const props = defineProps({
  bikeCode: {
    type: String,
    required: false
  },
  originBikeCode: {
    type: String,
    required: false
  },
  orderDetailStatus: {
    type: String,
    required: true
  }
})

const shouldRenderPopover = ref(false)
const bikeInfo = ref<(queryBikeTableCol & Record<string, any>) | null>(null)
// Computed property to check if the order is active or overdue
const isOrderActiveOrOverdue = computed(() => {
  return props.orderDetailStatus === '1' || props.orderDetailStatus === '5'
})

// Fields to display in the bike info
const bikeInfoFields = {
  bikeStatus: '车辆状态',
  lockStatus: '车锁状态',
  bikeOnlineStatus: '网络状态',
  powerLevel: '车辆电量',
  inputVoltage: '额定电压',
  bikeModel: '车辆型号',
  frameNumber: '车架号',
  carNumber: '牌照号'
}

// Method to get the style based on the field key
const getStyle = (key: string) => {
  const colorMap: Record<string, any> = {
    bikeStatus: bikeInfo.value?.bikeStatus === '空闲' ? '#00A870' : 'var(--xy-warning-light-color)',
    lockStatus: bikeInfo.value?.lockStatus === '0' ? '#00A870' : 'var(--xy-warning-light-color)',
    bikeOnlineStatus:
      bikeInfo.value?.bikeOnlineStatus === '1' ? '#00A870' : 'var(--xy-warning-light-color)',
    powerLevel: colorPowerLevel(bikeInfo.value?.powerLevel)
  }
  return { color: colorMap[key] || 'inherit' }
}

// Method to format the value based on the field key
const formatValue = (key: string) => {
  if (key === 'lockStatus') return changeLockStatus(bikeInfo.value?.lockStatus)
  if (key === 'bikeOnlineStatus') return changeBikeOnLine(bikeInfo.value?.bikeOnlineStatus)
  if (key === 'frameNumber') return bikeInfo.value?.frameNumber || '-'
  if (key === 'carNumber') return bikeInfo.value?.carNumber || '-'
  if (key === 'bikeModel') return bikeInfo.value?.bikeModel || '-'
  if (key === 'powerLevel') return bikeInfo.value?.powerLevel + '%' || '-'
  return bikeInfo.value ? bikeInfo.value[key] || '-' : '-'
}

/**
 * @description 车联网状态转换方法
 */
const changeBikeOnLine = (val: OnlineStatus | null | undefined) => {
  if (val == OnlineStatus.UnOnLine) {
    return '断网'
  } else if (val == OnlineStatus.OnLine) {
    return '联网'
  } else {
    return ''
  }
}

/**
 * @description 锁状态转换方法
 */
const changeLockStatus = (val: LockStatus | null | undefined) => {
  if (val == LockStatus.Locked) {
    return '上锁'
  } else if (val == LockStatus.Unlocked) {
    return '开锁'
  } else {
    return ''
  }
}
/**
 * @description 车辆电量UI
 */
const colorPowerLevel = (val: string | undefined) => {
  if (!val) return ''
  if (+val <= 20) {
    return '#FF6D75'
  } else if (+val <= 80) {
    return 'var(--xy-warning-light-color)'
  } else if (+val <= 100) {
    return '#00A870'
  }
}
// Event handler for fault record button
const router = useRouter()
const emits = defineEmits(['close'])
const faultRecord = () => {
  emits('close')
  router.push({
    name: 'FaultRecord',
    query: {
      bikeCode: bikeInfo.value?.bikeCode,
      bikeId: bikeInfo.value?.bikeId
    }
  })
}

// Event handler for bike locus button
const bikeLocus = () => {
  emits('close')
  router.push({
    name: 'LongBikeLocus',
    query: {
      bikeId: bikeInfo.value?.bikeId,
      orderId: bikeInfo.value?.orderId
    }
  })
}

// Event handler for bike location button
const bikeLocation = () => {
  emits('close')
  router.push({
    name: 'LongBikeLocation',
    query: {
      longtitude: bikeInfo.value?.longtitude,
      latitude: bikeInfo.value?.latitude,
      bikeCode: bikeInfo.value?.bikeCode
    }
  })
}

const getData = async () => {
  try {
    const res = await queryBike({
      token: getToken() ?? '',
      bikeCode: (props.bikeCode || props.originBikeCode) ?? '',
      storeId: '',
      type: BikeType.All,
      pageNum: 1,
      pageSize: 10
    })
    if (res.statusCode === '0') {
      bikeInfo.value = res.data.list[0]
      shouldRenderPopover.value = true
    }
  } catch (error) {
    console.error(error)
  }
}

// Mounted hook
watchEffect(() => {
  if (props.bikeCode || props.originBikeCode) {
    getData()
  }
})
</script>

<template>
  <template v-if="shouldRenderPopover">
    <el-popover placement="bottom" trigger="hover" popper-class="bike-code-popover" width="420px">
      <div class="bike-info">
        <div v-if="isOrderActiveOrOverdue" class="bike-info__details">
          <div
            v-for="(label, key) in bikeInfoFields"
            :key="key"
            class="bike-info__item"
            flex
            items-center
            flex-col
            justify-center
          >
            <span class="bike-info__label">{{ label }}</span>
            <span class="bike-info__value" :style="getStyle(key)">{{ formatValue(key) }}</span>
          </div>
        </div>
        <div class="bike-info__buttons" flex items-center>
          <el-button type="primary" @click="faultRecord">故障记录 ></el-button>
          <el-button type="primary" @click="bikeLocus">骑行轨迹 ></el-button>
          <el-button type="primary" @click="bikeLocation" v-if="isOrderActiveOrOverdue"
            >车辆位置 ></el-button
          >
        </div>
      </div>
      <template #reference>
        <el-icon><ArrowDown /></el-icon>
      </template>
    </el-popover>
  </template>
</template>

<style scoped></style>
